from twisted.internet import reactor, protocol, stdio
from Guild import *
import time
import sys
from twisted.protocols import basic
from sys import stdout
import thread
from Command import *

class Client(protocol.Protocol): 
	recv_data = ''	
	def connectionMade(self): 
		print "connection success"

		self.th = Command(self)
		self.th.setDaemon(True)
		self.th.start()

	def connectionLost(self, reason): 	
		print "connection lost" 

	def dataReceived(self, data) :
		# length of total(include header) : 4byte
		# tag_idl : 4byre
		# data 
		self.recv_data += data
		while len(self.recv_data) :
			if(len(self.recv_data) < 6) :
				print 'received data size is under \'length size\''
				break
		
			recv_bytes_tobe = int(struct.unpack('H', self.recv_data[1:3])[0]) + 3
			if(len(self.recv_data) < recv_bytes_tobe) :
				print 'received data size is under \'total size\''
				break;

			tag_id = struct.unpack('H', self.recv_data[4:6])[0]; 
			recv_data = self.recv_data[6:recv_bytes_tobe] 
			self.recv_data = self.recv_data[recv_bytes_tobe:]
			#print 'tag_id : ' + str(tag_id)
			#test_state += 1
			
			#dispatcher[tag_id](self, recv_data)
			self.th.getFunc(tag_id)(recv_data)
			#console(self)
			#print 'test_state : ' + str(test_state)
			#if test_state < len(test_sequence) :
				#test_sequence[test_state](self)
			
	def send(self, msg) :
		data = msg.Store()
		send_data  = struct.pack('B', 0xff)
		send_data += struct.pack('H', 3 + len(data))
		send_data += struct.pack('b', 0)
		send_data += struct.pack('H', msg.MSG_ID)
		send_data += data
		#self.transport.write(send_data)		
		self.transport.socket.sendall(send_data)

class ClientFactory(protocol.ClientFactory): 
	protocol = Client 
	def clientConnectionFailed(self, connector, reason): 
		print "Connection failed - goodbye!" 
		reactor.stop() 

	def clientConnectionLost(self, connector, reason): 
		print "Connection lost - goodbye!" 
		reactor.stop() # this connects the protocol to a server runing on port 8000 

def main():
	f = ClientFactory()
	reactor.connectTCP("localhost", 20004, f)
	reactor.run()

if __name__ == '__main__': 
	main() 
